package com.ljl.order.service.impl;

import com.ljl.basic.util.LoginContext;
import com.ljl.basic.util.PageList;
import com.ljl.order.domain.OrderPetAcquisition;
import com.ljl.order.dto.OrderDto;
import com.ljl.order.mapper.OrderPetAcquisitionMapper;
import com.ljl.order.query.OrderPetAcquisitionQuery;
import com.ljl.order.service.IOrderPetAcquisitionService;
import com.ljl.basic.service.impl.BaseServiceImpl;
import com.ljl.org.domain.Employee;
import com.ljl.org.domain.Shop;
import com.ljl.org.mapper.EmployeeMapper;
import com.ljl.org.mapper.ShopMapper;
import com.ljl.pet.domain.SearchMasterMsg;
import com.ljl.pet.mapper.PetMapper;
import com.ljl.pet.mapper.SearchMasterMsgMapper;
import com.ljl.user.domain.Logininfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;

/**
 * 业务实现类：
 */
@Service
public class OrderPetAcquisitionServiceImpl extends BaseServiceImpl<OrderPetAcquisition> implements IOrderPetAcquisitionService {
    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;

    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private PetMapper petMapper;


    @Override
    public PageList<OrderPetAcquisition> queryPage(OrderPetAcquisitionQuery query, HttpServletRequest request) {
        Logininfo logininfo = LoginContext.getLoginUser(request);
        Employee employee = employeeMapper.findByLogininfoId(logininfo.getId());
        System.out.println(employee);
        if (employee.getShop_id() != null){
            Shop shop = shopMapper.findById(employee.getShop_id());
            if (shop.getAdmin_id() != employee.getId()){
                query.setEmpId(employee.getId());
            }
            query.setShopId(shop.getId());
        }
        return super.queryPage(query);
    }

    @Override
    public void confirm(OrderDto orderDto) {
        Long orderId = orderDto.getId();
        Integer payType = orderDto.getPayType();
        BigDecimal money = orderDto.getMoney();

        //1.修改订单：state = 1，money，payType
        OrderPetAcquisition order = orderPetAcquisitionMapper.findById(orderId);
        order.setState(1);
        order.setPrice(money);
        order.setPaytype(payType);
        orderPetAcquisitionMapper.update(order);

        //2.修改寻主消息：state=2，note
        SearchMasterMsg msg = searchMasterMsgMapper.findById(order.getSearchMasterMsgId());
        msg.setState(2);
        msg.setNote("处理完成，交易成功");
        searchMasterMsgMapper.update(msg);

    }

    @Override
    public void del(Long id) {
        OrderPetAcquisition order = orderPetAcquisitionMapper.findById(id);
        searchMasterMsgMapper.reject(order.getSearchMasterMsgId());
        petMapper.del(order.getPetId());
        super.del(id);
    }
}
